<template>
  <el-card>
    <!-- 面包屑 -->
    <template #header>
      <el-breadcrumb separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </template>

    <!-- 搜索框 -->
    <el-row :gutter="10">
      <el-col :span="4">
        <el-input placeholder="请输入用户名" v-model="searchContent"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" plain @click="handleSearch()">搜索</el-button>
        <el-button type="primary" plain @click="addArticles()">
          添加用户
        </el-button>
      </el-col>
    </el-row>
    <!-- 将表格用卡片包裹会更美观 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column
        prop="user_id"
        label="序号"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="user_name"
        label="用户名"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="user_password"
        label="用户密码"
        width="120"
      ></el-table-column>

      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button
            @click="handleEdit(scope.$index, scope.row)"
            type="primary"
            size="small"
          >
            编辑
          </el-button>
          <el-button
            @click="handleDelete(scope.$index, scope.row)"
            type="danger"
            size="small"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="changePage"
    />
  </el-card>
  <!-- 新增用户对话框 -->
  <AddUser
    :dialogVisible="dialogVisible"
    @onCloseDialog="closeDialog"
  ></AddUser>
  <!-- 编辑用户对话框 -->
  <EditUser
    v-if="editDialogVisible === true"
    :editDialogVisible="editDialogVisible"
    :UserId="UserId"
    @onCloseEditDialog="closeEditDialog"
  ></EditUser>
</template>

<script>
import axios from 'axios'
import AddUser from '../components/UsersTool/AddUser.vue'
import EditUser from '../components/UsersTool/EditUser.vue'
import { onMounted, reactive, toRefs } from 'vue'
import { ElMessageBox, ElNotification } from 'element-plus'
// 已经在main.js中引入了全局的环境变量,所以这里就不用再写完整的地址了
// 判断搜索框是否为空,不为空则按搜索内容刷新页面
function loadData(state) {
  if (state.searchContent !== undefined && state.searchContent !== '') {
    // console.log(params)
    const page = state.currentPage
    const size = state.pageSize
    const title = state.searchContent
    axios
      .post(`/blog/username?page=${page}&size=${size}&user_name=${title}`)
      .then((res) => {
        console.log(res.data.result.data)
        console.log(res.data.result.total)
        state.tableData = res.data.result.data
        state.total = res.data.result.total
      })
  } else {
    const params = {
      page: state.currentPage,
      size: state.pageSize,
    }
    axios.get('/blog', { params }).then((res) => {
      // console.log(res.data.result.data)
      // console.log(res.data.result.total)
      state.tableData = res.data.result.data
      state.total = res.data.result.total
    })
  }
}
//搜索文章
function useSearch(state) {
  const handleSearch = () => {
    state.currentPage = 1
    const page = state.currentPage
    const size = state.pageSize
    const title = state.searchContent
    axios
      .post(`/blog/username?page=${page}&size=${size}&user_name=${title}`)
      .then((res) => {
        console.log(res.data.result.data)
        console.log(res.data.result.total)
        state.tableData = res.data.result.data
        state.total = res.data.result.total
      })
  }
  return {
    handleSearch,
  }
}
//编辑文章
function useEdit(state) {
  const handleEdit = (index, row) => {
    // console.log(index, row.user_id)
    state.editDialogVisible = true
    state.UserId = row.user_id
  }
  return {
    handleEdit,
  }
}
// 删除文章
function useDelete(state) {
  const handleDelete = (index, row) => {
    //console.log(index, row.user_id)
    ElMessageBox.confirm('确定要删除该用户吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      callback: (action) => {
        //判断点击的是确定还是取消,并给出反应
        if (action === 'confirm') {
          console.log(row.user_id)
          axios.delete(`/blog/${row.user_id}`).then((res) => {
            console.log(res.data.message)
            // 刷新页面
            if (res.data.message === '删除成功') {
              ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000,
              })
              // duration: 2000, 定时消失
              loadData(state)
            } else {
              ElNotification({
                title: '失败',
                message: '删除失败',
                type: 'error',
                duration: 2000,
              })
            }
          })
        }
      },
    })
  }
  return {
    handleDelete,
  }
}
export default {
  components: {
    AddUser,
    EditUser,
  },
  setup() {
    const state = reactive({
      searchContent: '', //搜索条件
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 4,
      dialogVisible: false, //控制新增对话框显隐
      editDialogVisible: false, //控制编辑对话框显隐
      UserId: 0, //要编辑的用户的编号
    })
    const url = import.meta.env.VITE_APP_URL
    onMounted(() => {
      loadData(state)
    })
    // 点击弹出对话框
    const addArticles = () => {
      state.dialogVisible = true
    }
    // 关闭新增对话框
    const closeDialog = (visible, data) => {
      state.dialogVisible = visible
      // 如果提交表单成功,关闭表单时把数据push到页面
      if (data !== undefined) {
        state.tableData.push(data)
        // 刷新页面
        loadData(state)
      }
    }
    // 关闭编辑对话框
    const closeEditDialog = (visible, data) => {
      //console.log(visible)
      state.editDialogVisible = visible
      //关闭表单后刷新页面显示最新更新的数据
      if (data !== undefined) {
        loadData(state)
      }
    }
    //
    const changePage = (page) => {
      state.currentPage = page
      loadData(state)
    }
    // 没有使用setup语法糖的话一定要写返回值
    return {
      // toRefs获取响应式数据
      ...toRefs(state),
      url,
      addArticles,
      closeDialog,
      closeEditDialog,
      ...useSearch(state),
      ...useEdit(state),
      ...useDelete(state),
      changePage,
    }
  },
}
</script>
